package com.chen.springboot.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.springboot.entity.Item;
import com.chen.springboot.entity.ItemDetail;
import com.chen.springboot.mapper.ItemDetailMapper;
import com.chen.springboot.mapper.ItemMapper;
import com.chen.springboot.service.ItemService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDetailMapper itemDetailMapper;

    @Override
    public List<Item> getAll(String search) {
        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery();
        wrapper.orderByDesc(Item::getCreated);
        if (!Strings.isBlank(search))
            wrapper.like(Item::getSellPoint, search);
        return itemMapper.selectList(wrapper);
    }

    @Override
    public void save(Item item) {
        Date currDate = new Date();
        item.setCreated(currDate);
        itemMapper.insert(item);
        // 新增空白的商品详情
        ItemDetail itemDetail = new ItemDetail();
        itemDetail.setItemId(item.getId());
        itemDetail.setItemDetail("<p></p>");
        itemDetail.setCreateTime(currDate);
        itemDetailMapper.insert(itemDetail);
    }

    @Override
    public void update(Item item) {
        item.setUpdated(new Date());
        itemMapper.updateById(item);
    }

    @Override
    public void delete(Long id) {
        itemMapper.deleteById(id);
    }

    @Override
    public Page<Item> findPage(Integer pageNum, Integer pageSize, String search) {
        //新建分页对象
        Page<Item> page = new Page<>(pageNum, pageSize);
        //新建模糊查询对象,这里有个注意事项，你模糊项查询的对应项不能为null，为null就查不出来
        //LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().like(User::getUsername, search);
        LambdaQueryWrapper<Item> queryWrapper = Wrappers.lambdaQuery();
        // 根据更新日期降序排列
        queryWrapper.orderByDesc(Item::getCreated);
        if (!search.isEmpty())
            queryWrapper.like(Item::getSellPoint, search);
        return itemMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Item findById(Integer id) {
        //找到ID相同的商品
        return itemMapper.selectOne(Wrappers.<Item>lambdaQuery().eq(Item::getId, id));
    }

    @Override
    public List<Item> findByCid(Integer cid) {
        LambdaQueryWrapper<Item> wrapper = Wrappers.<Item>lambdaQuery().eq(Item::getCid, cid);
        return itemMapper.selectList(wrapper);
    }
}
